$(function(){
	$('input[name="begDt"], input[name="endDt"]').datepicker({
		format: "yyyy-mm-dd",
	    todayBtn: "linked",
	    language: "zh-CN",
	    autoclose: true,
	    todayHighlight: true
	});

	var today = getDay(0);
	var yesterday = getDay(-1);
	$('input[name="begDt"]').val(yesterday);
	$('input[name="endDt"]').val(today);
});

var myApp = angular.module('myApp', [ 'ngGrid', 'ui.select2' ]);
myApp.controller('legsCtrl', function($scope, $http) {
	//global variable
	$scope.selectedRows = [];
	//init page item
	$scope.init = function() {
		$('input[name="pcTime"],input[name="rkTime"],input[name="ckTime"],input[name="fyTime"],input[name="ydTime"]').datetimepicker({
			minView: "month",
			format: "yyyy-mm-dd hh:ii",
		    todayBtn: "linked",
		    language: "zh-CN",
		    forceParse: false,
		    autoclose: true,
		    todayHighlight: true
		});
		httpPost($http, {"url":ctx+"/client/findListByFirst", "data": {"ffMap":{"st":0}}}, function(data){
			$scope.clientList=data.dt;
		}, function(){
			toastError("初始化客户列表失败。");
		});
		httpPost($http, {"url":ctx+"/constractor/findListBy", "data": {"ffMap":{"st":0}}}, function(data){
			$scope.constractorList = data.dt;
		}, function(){
			toastError("初始化承运商列表失败。");
		});
		httpPost($http, {"url":ctx+"/dict/findListBy", "data": {"ffMap":{"cd":"status","st":0}}}, function(data){
			$scope.statusList = data.dt;	
		}, function(){
			toastError("初始化订单状态列表失败。");
		});
		httpPost($http, {"url":ctx+"/dict/findListBy", "data": {"ffMap":{"cd":"shipment","st":0}}}, function(data){
			$scope.stList=[];
			for(var i=0;i<data.dt.length;i++){
				if(data.dt[i]['descr']=='shipment'||data.dt[i]['descr']=='shipmentEd'||data.dt[i]['descr']=='onway'||data.dt[i]['descr']=='arrive'){
					$scope.stList.push(data.dt[i]);
				}
			}	
		}, function(){
			toastError("初始化状态列表失败。");
		});
		httpPost($http, {"url":ctx+"/dict/findListBy", "data": {"ffMap":{"cd":"shipmentMethod","st":0}}}, function(data){
			$scope.shipment_methodList = data.dt;	
		}, function(){
			toastError("初始化运输方式列表失败。");
		});
	};
	$scope.init();
	
	//grid
	$scope.pagingOptions = {
		pageSizes : [ 20, 50, 100 ],
		pageSize : 20,
		currentPage : 1,
		onQueryFlag : false
	};
	$scope.$watch('pagingOptions', function(newVal, oldVal) {
		if (newVal !== oldVal/* && newVal.currentPage !== oldVal.currentPage*/) {
			$scope.query();
		}
	}, true);
	$scope.gridOptions = {
		data : 'dt',
		totalServerItems : 'tt',
		
		columnDefs : [
		{
			field : "id",
			displayName : "ID", visible : false
		},
		{
			field : "orderId",
			displayName : "orderId", visible : false
		},
		{
			field : "orderCd",
			displayName : "订单编号",width:160
		},
		{
			field : "legs_no",
			displayName : "分段订单号",width:160
		},
		{
			field : "statusName",
			displayName : "订单状态",width:160
		},
		{
			field : "stName",
			displayName : "状态",width:160
		},
		{
			field : "vocationName",
			displayName : "业务类型",width:160
		},
		{
			field : "platformName",
			displayName : "平台",width:160
		},
		{
			field : "clientName",
			displayName : "客户",width:160
		},
		{
			field : "constractorName",
			displayName : "承运商",width:160
		},
		{
			field : "vehicleCd",
			displayName : "运输工具",width:160
		},
		{
			field : "shipment_methodName",
			displayName : "运输方式",width:160
		},
		{
			field : "ftranslocationName",
			displayName : "出发地",width:160
		},
		{
			field : "ttranslocationName",
			displayName : "目的地",width:160
		},
		{
			field : "formName",
			displayName : "发货方名称",width:160
		},
		{
			field : "formlikeName",
			displayName : "发货方联系人",width:160
		},
		{
			field : "formPhone",
			displayName : "发货方电话",width:160
		},
		{
			field : "formAddr",
			displayName : "发货方地址",width:160
		},
		{
			field : "toName",
			displayName : "收货方名称",width:160
		},
		{
			field : "tolikeName",
			displayName : "收货方联系人",width:160
		},
		{
			field : "toPhone",
			displayName : "收货方电话",width:160
		},
		{
			field : "toAddr",
			displayName : "收货方地址",width:160
		},
		{
			field : "shipmentCd",
			displayName : "调度单号",width:160
		},
		{
			field : "shipmentType",
			displayName : "配载方式",width:160
		},
		{
			field : "quantity",
			displayName : "件数",width:160
		},
		{
			field : "weight",
			displayName : "重量",width:160
		},
		{
			field : "volume",
			displayName : "体积",width:160
		},
		{
			field : "palletsum",
			displayName : "托数",width:160
		},
		{
			field : "expense",
			displayName : "一口价",width:160
		},
		{
			field : "shipmentExpese",
			displayName : "调度单一口价",width:160
		},
		{
			field : "bag",
			displayName : "零箱数",width:160
		},
		{
			field : "pcTime",
			displayName : "派车时间",width:160,
			cellFilter: "date:'yyyy-MM-dd HH:mm:ss'"
		},
		{
			field : "rkTime",
			displayName : "车辆入库时间",width:160,
			cellFilter: "date:'yyyy-MM-dd HH:mm:ss'"
		},
		{
			field : "ckTime",
			displayName : "车辆出库时间",width:160,
			cellFilter: "date:'yyyy-MM-dd HH:mm:ss'"
		},
		{
			field : "ordertime",
			displayName : "开单时间",width:160,
			cellFilter: "date:'yyyy-MM-dd HH:mm:ss'"
		},
		{
			field : "billtime",
			displayName : "计费周期",width:160,
			cellFilter: "date:'yyyy-MM-dd HH:mm:ss'"
		},
		{
			field : "planltime",
			displayName : "计划发车时间",width:160,
			cellFilter: "date:'yyyy-MM-dd HH:mm:ss'"
		},
		{
			field : "leavetime",
			displayName : "发车时间",width:160,
			cellFilter: "date:'yyyy-MM-dd HH:mm:ss'"
		},
		{
			field : "planatime",
			displayName : "计划到达时间",width:160,
			cellFilter: "date:'yyyy-MM-dd HH:mm:ss'"
		},
		{
			field : "arrivetime",
			displayName : "到达时间",width:160,
			cellFilter: "date:'yyyy-MM-dd HH:mm:ss'"
		},
		],
		enablePaging : true,
		pagingOptions : $scope.pagingOptions,
		enableCellEdit:true,
		//enableCellSelection:true,
		//enablePinning : true,
		//showColumnMenu : true,
		//showGroupPanel : true,
		showSelectionCheckbox : true,
		selectedItems : $scope.selectedRows,
		plugins : [ /*new ngGridFlexibleHeightPlugin()*/ ],
		i18n: 'zh-cn', rowHeight : 20.2, footerRowHeight : 35,
		showFooter : true
	};

	$scope.query = function() {
		closeModal($("#queryFormModal"));
	
		var requestBody = {
			pageNb : $scope.pagingOptions.currentPage,
			pageSize : $scope.pagingOptions.pageSize,
			ffMap : $scope.queryForm
		};
		setTimeout(function() {
			httpPost($http, {"url":ctx + '/legs/findListBy', "data":requestBody, "ifBlock":true}, function(data){
				$scope.tt = data.tt;
				$scope.dt = data.dt;
				$scope.gridOptions.$gridScope.toggleSelectAll(false);
			}, function(errMsg){
				toastError("查询失败。" + errMsg);
			});
		}, 100);
	};
	//trigger query when currentPage not change
	$scope.onQuery = function(){
		$scope.pagingOptions.onQueryFlag = !$scope.pagingOptions.onQueryFlag;
		$scope.pagingOptions.currentPage = 1;
	};

	$scope.refresh=function(){
		$scope.onQuery();	
	};

	//utils
	$scope.onClearSelectedRows = function() {
		$scope.gridOptions.$gridScope.toggleSelectAll(false);
	};
	
	//crud
	$scope.onOpenQueryFormModal = function() {
		openModal($("#queryFormModal"));
	};
	//派车确认
	$scope.onOpenEditFormModalPc = function() {
		$scope.editFormPc={};
		var date= (new Date());
		var now = date.getFullYear() + "-" + (parseInt(date.getMonth()) + 1) +"-"+((date.getDate() > 9) ? date.getDate() : "0" + date.getDate())+" "+((date.getHours()> 9) ? date.getHours() : "0" + date.getHours())+":"+((date.getMinutes() > 9) ? date.getMinutes() : "0" + date.getMinutes());
		$scope.editFormPc.pcTime=now;
		openModal($("#editFormModalPc"));
	};
	$scope.pcConfirm=function(){
		closeModal($("#editFormModalPc"));
		var selectedRowIds = [];
		var selectedShipmentIds = [];
		var orderIds=[];
		$.each($scope.selectedRows, function(idx, obj){
			selectedRowIds.push(obj.id);
			orderIds.push($scope.selectedRows[idx]['orderId']);
			var shipmentId=$scope.selectedRows[idx]['shipmentId'];
			if(jQuery.inArray( shipmentId, selectedShipmentIds ) < 0){
				selectedShipmentIds.push(shipmentId);
			}
		});
		httpPost($http, {"url":ctx + '/legs/updTime',"data": {"ffMap":{"ids":selectedRowIds,"pcTime":$scope.editFormPc.pcTime}},"ifBlock":true}, function(data){
			httpPost($http, {"url":ctx + '/legs/updStatusPcDt',"params": {"ids":selectedShipmentIds,"pcTime":$scope.editFormPc.pcTime,"orderIds":orderIds},"ifBlock":true}, function(data){
				$scope.query();
			});
		});
	};
	//车辆入库
	$scope.onOpenEditFormModalIn = function() {
		$scope.editFormRk={};
		var date= (new Date());
		var now = date.getFullYear() + "-" + (parseInt(date.getMonth()) + 1) +"-"+((date.getDate() > 9) ? date.getDate() : "0" + date.getDate())+" "+((date.getHours()> 9) ? date.getHours() : "0" + date.getHours())+":"+((date.getMinutes() > 9) ? date.getMinutes() : "0" + date.getMinutes());
		$scope.editFormRk.rkTime=now;
		openModal($("#editFormModalIn"));
	};
	$scope.rkConfirm=function(){
		closeModal($("#editFormModalIn"));
		var selectedRowIds = [];
		var selectedShipmentIds = [];
		var orderIds=[];
		$.each($scope.selectedRows, function(idx, obj){
			selectedRowIds.push(obj.id);
			orderIds.push($scope.selectedRows[idx]['orderId']);
			var shipmentId=$scope.selectedRows[idx]['shipmentId'];
			if(jQuery.inArray( shipmentId, selectedShipmentIds ) < 0){
				selectedShipmentIds.push(shipmentId);
			}
		});
		httpPost($http, {"url":ctx + '/legs/updTime',"data": {"ffMap":{"ids":selectedRowIds,"rkTime":$scope.editFormRk.rkTime}},"ifBlock":true}, function(data){
			httpPost($http, {"url":ctx + '/legs/updStatusRkDt',"params": {"ids":selectedShipmentIds,"rkTime":$scope.editFormRk.rkTime,"orderIds":orderIds},"ifBlock":true}, function(data){
				$scope.query();
			});
		});
	};
	//车辆出库
	$scope.onOpenEditFormModalOut = function() {
		$scope.editFormCk={};
		var date= (new Date());
		var now = date.getFullYear() + "-" + (parseInt(date.getMonth()) + 1) +"-"+((date.getDate() > 9) ? date.getDate() : "0" + date.getDate())+" "+((date.getHours()> 9) ? date.getHours() : "0" + date.getHours())+":"+((date.getMinutes() > 9) ? date.getMinutes() : "0" + date.getMinutes());
		$scope.editFormCk.ckTime=now;
		openModal($("#editFormModalOut"));
	};
	$scope.ckConfirm=function(){
		closeModal($("#editFormModalOut"));
		var selectedRowIds = [];
		var selectedShipmentIds = [];
		var orderIds=[];
		$.each($scope.selectedRows, function(idx, obj){
			selectedRowIds.push(obj.id);
			orderIds.push($scope.selectedRows[idx]['orderId']);
			var shipmentId=$scope.selectedRows[idx]['shipmentId'];
			if(jQuery.inArray( shipmentId, selectedShipmentIds ) < 0){
				selectedShipmentIds.push(shipmentId);
			}
		});
		httpPost($http, {"url":ctx + '/legs/updTime',"data": {"ffMap":{"ids":selectedRowIds,"ckTime":$scope.editFormCk.ckTime}},"ifBlock":true}, function(data){
			httpPost($http, {"url":ctx + '/legs/updStatusCkDt',"params": {"ids":selectedShipmentIds,"ckTime":$scope.editFormCk.ckTime,"orderIds":orderIds},"ifBlock":true}, function(data){
				$scope.query();
			});
		});
	};
	
	//发运确认
	$scope.onOpenEditFormModalFy = function() {
		$scope.editFormFy={};
		var date= (new Date());
		var now = date.getFullYear() + "-" + (parseInt(date.getMonth()) + 1) +"-"+((date.getDate() > 9) ? date.getDate() : "0" + date.getDate())+" "+((date.getHours()> 9) ? date.getHours() : "0" + date.getHours())+":"+((date.getMinutes() > 9) ? date.getMinutes() : "0" + date.getMinutes());
		$scope.editFormFy.fyTime=now;
		openModal($("#editFormModalFy"));
	};
	$scope.fyConfirm=function(){
		closeModal($("#editFormModalFy"));
		var selectedRowIds = [];
		var selectedShipmentIds = [];
		var orderIds=[];
		$.each($scope.selectedRows, function(idx, obj){
			selectedRowIds.push(obj.id);
			orderIds.push($scope.selectedRows[idx]['orderId']);
			var shipmentId=$scope.selectedRows[idx]['shipmentId'];
			if(jQuery.inArray( shipmentId, selectedShipmentIds ) < 0){
				selectedShipmentIds.push(shipmentId);
			}
		});
		httpPost($http, {"url":ctx + '/legs/updStByIds',"params": {"ids":selectedRowIds,"st":"onway"},"ifBlock":true}, function(data){
			
		});
		httpPost($http, {"url":ctx + '/legs/updTime',"data": {"ffMap":{"ids":selectedRowIds,"fyTime":$scope.editFormFy.fyTime}},"ifBlock":true}, function(data){
			httpPost($http, {"url":ctx + '/legs/updStatusFyDt',"params": {"ids":selectedShipmentIds,"fyTime":$scope.editFormFy.fyTime,"orderIds":orderIds},"ifBlock":true}, function(data){
				$scope.query();
			});
		});
	};
	
	//运抵确认
	$scope.onOpenEditFormModalYd = function() {
		$scope.editFormYd={};
		var date= (new Date());
		var now = date.getFullYear() + "-" + (parseInt(date.getMonth()) + 1) +"-"+((date.getDate() > 9) ? date.getDate() : "0" + date.getDate())+" "+((date.getHours()> 9) ? date.getHours() : "0" + date.getHours())+":"+((date.getMinutes() > 9) ? date.getMinutes() : "0" + date.getMinutes());
		$scope.editFormYd.ydTime=now;
		openModal($("#editFormModalYd"));
	};
	$scope.ydConfirm=function(){
		closeModal($("#editFormModalYd"));
		var selectedRowIds = [];
		var selectedShipmentIds = [];
		var orderIds=[];
		$.each($scope.selectedRows, function(idx, obj){
			selectedRowIds.push(obj.id);
			orderIds.push($scope.selectedRows[idx]['orderId']);
			var shipmentId=$scope.selectedRows[idx]['shipmentId'];
			if(jQuery.inArray( shipmentId, selectedShipmentIds ) < 0){
				selectedShipmentIds.push(shipmentId);
			}
		});
		httpPost($http, {"url":ctx + '/legs/updStByIds',"params": {"ids":selectedRowIds,"st":"arrive"},"ifBlock":true}, function(data){
			
		});
		httpPost($http, {"url":ctx + '/legs/updTime',"data": {"ffMap":{"ids":selectedRowIds,"ydTime":$scope.editFormYd.ydTime}},"ifBlock":true}, function(data){
			httpPost($http, {"url":ctx + '/legs/updStatusYdDt',"params": {"ids":selectedShipmentIds,"ydTime":$scope.editFormYd.ydTime,"orderIds":orderIds},"ifBlock":true}, function(data){
				$scope.query();
			});
		});
	};
	
	$scope.onOpenEditFormModal = function(type, id) {
		if(type=="add"){
			$scope.editForm = {};
		}else if(type=="upd"){
			//if($scope.selectedRows.length != 1) { toastWarning("请选择一笔记录进行编辑。"); return; }
			httpGet($http, {"url":ctx+'/legs/id/'+id, "ifBlock":true}, function(data){
				$scope.editForm = data.dt;
			}, function(errMsg){
				toastWarning("查询此笔记录失败。");
			});
		}
		openModal($("#editFormModal"));
	};
	$scope.onSaveEditForm = function(){
		closeModal($("#editFormModal"));
		httpPost($http, {"url":ctx + '/legs/save', "data":$scope.editForm, "ifBlock":true}, function(data){
			toastSuccess("保存成功");
			$scope.query();
		}, function(errMsg){
			toastError("保存失败,您输入的信息有误，请检查正确之后再保存。" + errMsg);
		});
	};
	$scope.onOpenDelFormModal = function() {
		var selectedRowsLength = $scope.selectedRows.length;
		if(selectedRowsLength < 1) { toastWarning("请至少选择一笔记录进行删除。"); return; }
		dialogConfirm("是否确认删除选择的"+selectedRowsLength+"笔记录？", function(){
			var selectedRowsId = [];
			$.each($scope.selectedRows, function(idx, obj){
				selectedRowsId.push(obj.id);
			});
			httpPost($http, {"url":ctx + '/legs/updStByIds', "params":{"ids":selectedRowsId, "st":1}, "ifBlock":true}, function(data){
				toastSuccess("删除成功");
				$scope.query();
			}, function(errMsg){
				toastError("删除失败。" + errMsg);
			});
		});
	};
});